package com.winning.devops.batch.job;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * job 配置
 *
 * @author chensj
 * @date 2020-02-28 11:12
 */
@Configuration
@EnableBatchProcessing
public class JobConfiguration {

    /**
     * 创建Job的bean
     */
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    /**
     * job 由step组成
     * 创建Step 对象的bean
     */
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    /**
     * 创建任务
     *
     * @return job
     */
    @Bean
    public Job helloWorldJob() {

        return jobBuilderFactory
                // 任务名称
                .get("helloWorldJob")
                // 第一个任务
                .start(first())
                // 创建任务
                .build();
    }

    /**
     * step 步骤1
     *
     * @return step
     */
    @Bean
    public Step first() {
        return stepBuilderFactory
                .get("first")
                // 第一种 tasklet
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                        // 具体的执行代码
                        System.out.println("Hello World");
                        // 返回值表示是否执行下面的step
                        return RepeatStatus.FINISHED;
                    }
                })
                // 第二种
                //.chunk()
                .build();
    }
}
